package com.fz.security.utils;


import com.fz.entity.member.Member;
import com.fz.security.config.SecurityProperties;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.*;

@Slf4j
@Component
public class JwtTokenUtils implements InitializingBean{
    private static final String AUTHORITIES_KEY = "auth";
    private final SecurityProperties properties;
    private Key key;

    public JwtTokenUtils(SecurityProperties properties) {
        this.properties = properties;
    }


    public void afterPropertiesSet() {
        byte[] keyBytes = Decoders.BASE64.decode(properties.getBase64Secret());
        this.key = Keys.hmacShaKeyFor(keyBytes);
    }


    /**
     * @方法描述:  生成token信息 并存入jwt缓存
     * @参数:
     * @返回值:
     * @创建人: I am God
     * @创建时间:: 2021/3/18
     */
    public String createToken(Member member) {
        long now = (new Date()).getTime();
        Date validity = new Date(now + properties.getTokenValidityInSeconds());
        String token = Jwts.builder()
                .setSubject(member.getUid() + member.getMobilePhone())
                .claim(AUTHORITIES_KEY, member.getMobilePhone())
                .signWith(key, SignatureAlgorithm.HS512)
                .setExpiration(validity)
                .compact();
        return token;
    }


}
